<template>
  <div style="display: flex;flex-direction: column;align-items: center">
    <div v-if="hasForm" class="searchForm">
        <slot></slot>
        <!--<div v-if="!tableConfig.isNotSearch" :class="isFeed ? 'btn-box' : 'lineFeed'">
          <el-button type="primary" @click="handleSearch()">查询</el-button>
        </div>-->

      <div  style="display: flex;margin:0 0 8px 18px;justify-content: flex-end">
          <slot name="operatorTemp">
            <el-button type="primary" @click="handleSearch" size="mini">查询</el-button>
            <el-button  type="plain" @click="resetForm"  size="mini">重置</el-button>

            <el-button  type="plain" @click="refreshTableData" size="mini">刷新</el-button>
          </slot>
      </div>
    </div>

    <div v-if="tableConfig.topOperate" class="tab-operator">
      <div>
        <slot name="leftTableExtraOperate"></slot>
      </div>
      <div>
        <slot name="rightTableExtraOperate"></slot>
      </div>
    </div>

<!--    <div style="height:10px;width:100%;background-color:#bfa !important;"></div>-->
    <!--<div v-if="!tableConfig.isTreeTable" class="table-box">-->
    <div class="table-box">
      <!--普通列表-->
      <el-table
        border
        stripe
        row-id="resourceID"
        row-key="resourceID"
        ref="searchTable"
        :data="tableData"
        v-loading="tableLoading"
        element-loading-text="加载中，请稍后..."
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        class="table temp-table"
        :style="cssVars"
        :max-height="tableConfig.tableHeight"
        :header-cell-style="{background:'#F5F5F5'}"
        highlight-hover-row
        @select="handleSelectionChange"
        @select-all="handleSelectionChange">
        <!--   <el-table-column v-if="tableConfig.isIndex" label="序号" type="index" width="55">
             <template slot-scope="scope">
               {{(scope.$index + 1) + pagination.pageSize * (pagination.pageNumber - 1)}}
             </template>
           </el-table-column>-->
     <!--   <template slot="empty">
          <img src="@/assets/kong_status.png" style="width: 50%;height: 50%" alt>
          <div>暂无数据</div>
        </template>-->
        <el-table-column v-if="!tableConfig.isRadio" type="selection" reserve-selection width="40"  fixed="left"></el-table-column>

        <el-table-column v-if="tableConfig.isRadio" width="55"  fixed="left">
          <template slot-scope="scope">
            <!--              <el-radio :label="scope.$index" v-model="templateRadio" @change.native="getTemplateRow(scope.$index, scope.row)">&nbsp</el-radio>-->
            <el-radio :label="scope.$index" v-model="templateRadio" @change.native="getTemplateRow(scope.$index, scope.row)"></el-radio>
          </template>
        </el-table-column>

        <template v-for="(item, index) in tableConfig.columnConfig">
          <!---->
          <template v-if="item.isSlot">
            <el-table-column
              :key="index"
              :formatter="item.formatter"
              :width="item.width"
              :sortable="item.isSort"
              :prop="item.prop"
              :label="item.label"
              show-overflow-tooltip
              show-header-overflow>
              <template slot-scope="scope">
                <slot v-if="item.isSlot" :name="item.prop" :row="scope.row" />
              </template>
            </el-table-column>
          </template>

          <!--非操作栏-->
          <template v-else>
            <el-table-column
              v-if="item.prop !== 'operator'"
              :key="index"
              :fixed="item.fixed"
              :formatter="item.formatter"
              :width="item.width"
              :sortable="item.isSort"
              :prop="item.prop"
              :label="item.label"
              show-overflow-tooltip
              show-header-overflow>
              <!--<slot v-if="item.formatter" :name="item.prop" v-html="item.formatter"></slot>-->
            </el-table-column>
            <!--操作栏-->
            <el-table-column
              v-if="item.prop === 'operator'"
              :key="index"
              :fixed="item.fixed"
              :width="item.width"
              :prop="item.prop"
              :label="item.label"
              class="operator">
              <template slot-scope="scope">
                <slot name="tableOperator" :row="scope.row" />
              </template>
            </el-table-column>
          </template>
        </template>
      </el-table>

    </div>

    <div class="pagination" style="align-self: flex-end">
      <el-pagination
        v-show="pagination.total>0"
        :background="background"
        :current-page.sync="pagination.currentPage"
        :page-size.sync="pagination.pageSize"
        :layout="layout"
        :page-sizes="pagination.pageOptions"
        :total="pagination.total"
        v-bind="$attrs"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
  import axios from "axios";

  export default {
    name: "TablePagination",
    props: {
      hasForm:{
        type:Boolean,
        default:false
      },
      loading:{
        type:Boolean,
        default:false
      },
    /*  tableData:{
        type:Array,
        default() {
          return [];
        }
      },*/
      tableConfig: {
        type: Object,
        default() {
          return {}
        }
      },
      tableType:{

      },
    /*  isFeed: {
        type: Boolean,
        default: true
      },*/

/*      // 分页配置
      total: {
        required: true,
        type: Number
      },
      page: {
        type: Number,
        default: 1
      },
      limit: {
        type: Number,
        default: 20
      },
      pageSizes: {
        type: Array,
        default() {
          return [10, 20, 30, 50]
        }
      },*/
      layout: {
        type: String,
        default: 'total, sizes, prev, pager, next, jumper'
      },
      background: {
        type: Boolean,
        default: true
      },
      autoScroll: {
        type: Boolean,
        default: true
      },
      hidden: {
        type: Boolean,
        default: false
      },
      searchFormData:{
        type:Object,
        default:()=>{}
      },
      createUser:{
        type:String
      }
    },
    computed:{
     /* systemID(){
        return this.$store.getters.activeSystem
      },*/
      tablePadding(){
        console.log("leftTreeWidth latest",this.$store.getters.leftTreeWidth)
        // return (this.$store.getters.tablePadding) +"px"
        return "12px"
      },
      cssVars() {
        console.log("this.tablePadding",this.tablePadding)
        return {
          '--padding': `${this.tablePadding} 0`,
          "width": "100%"
        };
      }
    },
    created() {



    },
    mounted() {
      console.log("首次加载")
      this.handleSearch()
      // axios.post(this.tableConfig.requestUrl, {
      //   // 参数 是表单数据+分页数据
      //   pageNum: this.pagination.currentPage,
      //   pageSize:this.pagination.pageSize,
      //   requestBody:{
      //     planName:"",
      //     createUser:this.createUser
      //   }
      // },{
      //   headers: {
      //     'Content-Type': 'application/json'
      //   }
      // }).then(res => {
      //   console.log("系统数据", res.data)
      //   this.tableData = res.data.obj.content || []
      //   this.pagination.total = res.data.obj.total*1 ||  res.data.obj.totalElements*1
      //   this.tableLoading = false
      // }).catch(()=>{})
    },
    data() {
      return {
        tableLoading:false,
        tableData:[
          {}
        ],
        pagination: {
          total: 0, // 总数
          pageSize: 20, // 页面多少条数据
          currentPage: 1, // 当前在哪页
          pageOptions: [10, 20, 50, 100]// 页面选项
        },
        templateRadio: '',
        selectedRows: [], // 多选
        selectedRow:[]   // 单选
      }
    },
    methods:{
      // clearSelection
      clearSelection(){
        this.$refs.searchTable.clearSelection()
      },
      // 多选勾选数据
      handleSelectionChange(rows) {
        console.log("rows",rows)
        // this.selectedRows = []
        this.selectedRows = rows
        this.$emit("handleSelectionChange",rows)
      },
      // 单选
      getTemplateRow(index, row) {
        console.log("index,row",index,row)
        this.selectedRow = []
        this.selectedRow.push(row)
        console.log(this.selectedRow)
        this.$emit("getTemplateRow",row)
      },


      handleSizeChange(val) {
        console.log(val)
        this.pagination.currentPage = 1
        this.pagination.pageSize = val
        console.log(this.currentPage)
        this.handleSearch()
        // this.$emit('getList', { page: 1, limit: val })
        // this.$emit('getList', { page: this.currentPage, limit: val })
      },

      handleCurrentChange(val) {
        console.log(val)
        this.pagination.currentPage = val
        this.handleSearch()
        // console.log(this.pageSize)
        // this.$emit('getList', { page: val, limit: this.pageSize })
      },

      handleSearch(){
        // console.log(this.$parent.$refs)
        console.log(this.searchFormData)
        // alert('submit!');
        this.getList()
        // this.$parent.$refs.ruleForm.validate((valid) => {
        //   console.log(this.searchFormData)
        //
        //   if (valid) {
        //     if(typeof this.searchFormData.startTime == "object"){
        //       this.searchFormData.startTime = this.time(this.searchFormData.startTime)
        //     }
        //     if (typeof this.searchFormData.endTime == "object"){
        //       this.searchFormData.endTime = this.time(this.searchFormData.endTime)
        //     }
        //
        //   } else {
        //     console.log('error submit!');
        //     return false;
        //   }
        // });
      },
      getList(){
        // 得到分页的参数
        console.log(this.pagination)
        let params = {

          pageSize: this.pagination.pageSize,
          pageNum: this.pagination.currentPage,
          requestBody:{
            ...this.searchFormData,
          }
        }
        console.log("查询的参数", params)
        this.tableLoading = true

        axios.post(this.tableConfig.requestUrl, {
          // 参数 是表单数据+分页数据
          ...params
        },{
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => {
          console.log("menuData", res.data)
          this.tableData = res.data.obj.content ||res.data.obj.list || []
          this.pagination.total = res.data.obj.total*1 ||  res.data.obj.totalElements*1
          this.tableLoading = false
        }).catch(()=>{})
      },
      refreshTableData(){
        this.handleSearch()
      },
      resetForm(){
        // console.log( this.$parent)
        // console.log( this.$parent.$parent)
        for (const key in this.$parent.searchFormData) {
          // if (key!== "sid"){
          //
          // }
          this.$parent.searchFormData[key] = ""
        }
        // this.$parent.searchFormData.sid = this.systemID
        this.pagination.currentPage = 1
        this.getList()
      },

      // 时间处理函数
      time(time, fmt = 'YYYY-MM-DD') { // YYYY-MM-DD || YYYY-MM-DD hh:mm:ss
        if (!time) return 0
        let date = new Date(time - 0);
        if (/(Y+)/.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, date.getFullYear() + '').substr(4 - RegExp.$1.length)
        }
        let o = {
          'M+': date.getMonth() + 1,
          'D+': date.getDate(),
          'h+': date.getHours(),
          'm+': date.getMinutes(),
          's+': date.getSeconds()
        }
        for (let key in o) {
          if (new RegExp(`(${key})`).test(fmt)) {
            let str = o[key] + ''
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str))
          }
        }

        return fmt
      },
      // 时间处理函数
      padLeftZero (str) {
        return ('00' + str).substr(str.length)
      }
    }
  }
</script>

<style scoped lang="scss">
  /*表格换行显示*/
  ::v-deep .el-table thead {
    height: 50px;
    color: #000;
    background-color: red;
    font-weight: bold;
  }


  .el-table .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  /*隐藏单选框的文字*/
  ::v-deep .el-radio__label{
    display: none;
  }

  .pagination-container {
    background: #fff;
    padding: 32px 16px;
  }
  .pagination-container.hidden {
    display: none;
  }

  .searchForm {
    width: 98%;
    margin-top: 10px;
    min-height: 120px;
    background-color: #fff;
    box-shadow: 3px 3px 3px 1px rgba(224, 200, 209, 0.2);
    color: silver;
    padding: 15px 15px 0 5px;
    border: 1px solid #e8e8e8;
    .el-form-item {
      margin-bottom: 6px;
    }
    border-radius: 3px;
  }
  .table-box{
    width: 98%;
    /*height: 600px;*/
    /*overflow: auto;*/
    border-radius: 3px;
    box-shadow: 3px 3px 3px 1px rgba(224, 200, 209, 0.2);

  }
  .tab-operator{
    width: 98%;
    display: flex;
    justify-content: space-between;
    margin: 10px 0;
  }

  .pagination{
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    /*box-shadow: 3px 3px 3px 1px rgba(0, 0, 200, 0.2);*/

  }
  ::v-deep .el-pagination.is-background .el-pager li{
    /*background-color: rgba(0,0,0,0);*/
  }
  ::v-deep .el-pager li{
    /*background-color: #4A9FF9!important;*/
    border: 1px solid lightgrey;
  }
  ::v-deep .el-table--small .el-table__cell{
    padding: var(--padding) !important;;
  }
  // 滚动条的宽度
 /* /deep/ .el-table__body-wrapper::-webkit-scrollbar {
    width: 0px; // 横向滚动条
    height: 10px; // 纵向滚动条 必写
  }*/

  //注意:hover
 /* /deep/ .el-table__body-wrapper:hover::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条 必写
  }
*/

  // 滚动条的滑块
  /*/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
  }*/

</style>
